import axios from 'axios'
import {getToken,getCurrentUrl}  from '@/libs/util'
import globalConfig from '@/config'
import {Modal} from 'iview'
// import { Spin } from 'iview'

class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const configuration = {
      baseURL: this.baseUrl,
      headers: {
        //token
        'token': getToken()
      }
    }
    return configuration
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const data  = res.data;
      if(data.status !='success'){
        let error = data.error;
        if(data.status=='fail'){
          Modal.warning({
            title:'错误提示',
            content:error.message,
            closable:true
          });
        }else if(data.status == 'error'){
          Modal.error({
            title:'错误提示',
            content:error.message,
            closable:true
          });
        }
        return Promise.reject(error)
      }
      return data.body
    }, error => {      
      this.destroy(url)
      let response = error.response
      //401 未授权，跳转到登陆页面
      if(response.status===401){     
        Modal.confirm({
          title:'未验证',
          content:'未登陆或者token失效, 请单击确认按钮，跳转登陆验证!',
          closable:true,
          onOk:function(){
            let currentUrl = getCurrentUrl()
            let loginUrl = encodeURIComponent(currentUrl);
            window.location.href = globalConfig.loginUrl+'?redirect_uri='+loginUrl;
          }          
        });           
      }      
      return Promise.reject(error) 
    })
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
